import React from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import { getDetailByIdApi, deleteStuByIdApi } from "../api/stuApi";
/**
 * 学生详情组件
 */
function Detail(props) {
  const { id } = useParams();
  const navigate = useNavigate();
  const [stu, setStu] = useState({
    id: "",
    name: "",
    age: "",
    phone: "",
    email: "",
    address: "",
    gender: "",
  });
  useEffect(() => {
    getDetailByIdApi(id).then(({ data }) => {
      setStu(data);
    });
  }, [id]);
  function deleteStu() {
    if (window.confirm("are you sure delete this student?")) {
      deleteStuByIdApi(id).then(() => {
        navigate("/home", {
          state: {
            alert: "delete success",
            type: "info",
          },
        });
      });
    }
  }
  return (
    <div>
      <div className="detail container">
        <button className="btn btn-info" onClick={() => navigate("/home")}>
          back
        </button>
        <h1 className="page-header">{stu.name + "'s personal infomations"}</h1>
        <div className="header-btn">
          <button
            className="btn btn-primary"
            onClick={() => navigate(`/edit/${id}`)}
          >
            edit
          </button>
          <button className="btn btn-danger" onClick={deleteStu}>
            delete
          </button>
        </div>

        <ul className="list-group">
          <li className="list-group-item">
            <span className="glyphicon glyphicon-user">name:{stu.name}</span>
          </li>
          <li className="list-group-item">
            <span className="glyphicon glyphicon-star">age:{stu.age}</span>
          </li>
          <li className="list-group-item">
            <span className="glyphicon glyphicon-heart">
              gender:{stu.gender}
            </span>
          </li>
        </ul>
        <ul className="list-group">
          <li className="list-group-item">
            <span className="glyphicon glyphicon-phone">phone:{stu.phone}</span>
          </li>
          <li className="list-group-item">
            <span className="glyphicon glyphicon-envelope">
              email:{stu.email}
            </span>
          </li>
        </ul>

        <ul className="list-group">
          <li className="list-group-item">
            <span className="glyphicon glyphicon-home">
              address:{stu.address}
            </span>
          </li>
        </ul>
      </div>
    </div>
  );
}

export default Detail;
